package icu.wangrui.bookstore.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import icu.wangrui.bookstore.dto.BookDTO;
import icu.wangrui.bookstore.mapper.BookMapper;
import icu.wangrui.bookstore.pojo.Book;
import icu.wangrui.bookstore.pojo.User;
import icu.wangrui.bookstore.service.IBookService;
import org.apache.ibatis.jdbc.Null;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class BookServiceImpl implements IBookService {
    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


/**
 * @Author 王锐
 * @Date 2020/4/30 0030 9:02
 * @Description 使用Mybatis分页插件查询
 * @Param [page]
 * @Return java.util.List<icu.wangrui.bookstore.dto.BookDTO>
 * @Since version-1.0
 */
    @Override
    public List<BookDTO> showAllBook(Integer page) {
        PageHelper.startPage(page,2);//查询第一页显示两条
        List<Book> books = bookMapper.showAllBook();


        List<BookDTO> questionDTOList = new ArrayList<>();
        PageInfo<Book> bookPageInfo = new PageInfo<>(books,5);
/*        System.out.println("导航栏："+ Arrays.toString(bookPageInfo.getNavigatepageNums()));
        System.out.println("当前页码："+bookPageInfo.getPageNum());
        System.out.println("每页几条："+bookPageInfo.getPageSize());
        System.out.println("总页数："+bookPageInfo.getPages());
        System.out.println("有没有上一页："+bookPageInfo.isHasPreviousPage());
        System.out.println("有没有下一页："+bookPageInfo.isHasNextPage());*/
            BookDTO bookDTO = new BookDTO();
            bookDTO.setBooks(books);
            bookDTO.setBookPageInfo(bookPageInfo);
        questionDTOList.add(bookDTO);
        return questionDTOList;
    }

    @Override
    public List<Book> adminShowAllBook() {
        List<Book> books = bookMapper.showAllBook();
        return books;
    }

    @Override
    public Boolean updateBookByIsbn(String isbn,Double price) {
        return bookMapper.updateBookByIsbn(isbn,price);
    }

    @Override
    public Boolean addBook(Book book) {
        Boolean aBoolean = bookMapper.addBook(book);
        return aBoolean;
    }

    /**
     * @Author 王锐
     * @Date 2020/4/30 0030 13:31
     * @Description es普通查询
     * @Param
     * @Return
     * @Since version-1.0
     */
    public List<Map<String,Object>> searchPage(Integer pageNo, Integer pageSize) throws IOException {
        if (pageNo<=1){
            pageNo=1;
        }

        //条件搜索
        SearchRequest searchRequest = new SearchRequest("tedu_bookstore");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();


        //分页
        sourceBuilder.from(pageNo-1);
        sourceBuilder.size(pageSize);

        //精准匹配
        MatchAllQueryBuilder termQueryBuilder = QueryBuilders.matchAllQuery();
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            list.add(documentFields.getSourceAsMap());
        }
        return list;
    }



/**
 * @Author 王锐
 * @Date 2020/4/30 0030 9:08
 * @Description 使用elasticsearch高亮查询
 * @Param [keyword, pageNo, pageSize]
 * @Return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
 * @Since version-1.0
 */


    @Override
    public List<Map<String, Object>> searchPageHighlightBuilder(String keyword, Integer pageNo, Integer pageSize) throws IOException {
        if (pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("tedu_bookstore");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo-1);
        sourceBuilder.size(pageSize);

        /**
         * 使用QueryBuilder
         * termQuery("key", obj) 完全匹配
         * termsQuery("key", obj1, obj2..)   一次匹配多个值
         * matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性
         * multiMatchQuery("text", "field1", "field2"..);  匹配多个字段, field有通配符忒行
         * matchAllQuery();         匹配所有文件
     */
        //精准匹配

        MatchQueryBuilder termQueryBuilder = QueryBuilders.matchQuery("title", keyword);
        //MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false);//多个高亮显示
        highlightBuilder.preTags("<span style='color:red;font:18px simhei'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);//坑

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果
            //解析高亮的字段，将原来的字段转换为我们高亮的字段即可
            if (title != null) {
                Text[] fragments = title.fragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                sourceAsMap.put("title",n_title);//高亮字段替换原来的字段
            }
            list.add(sourceAsMap);
        }
        return list;
    }

    @Override
    public Book showBookByIsbn(String isbn) {
        Book book = bookMapper.showBookByIsbn(isbn);
        return book;
    }

    @Override
    public List<Book> showBookByUser(User loginUser) {
        return bookMapper.showBookByUser(loginUser);
    }

    @Override
    public boolean selectCollectByPhoneAndIsbn(String phone, String isbn) {
        Boolean book = bookMapper.selectCollectByPhoneAndIsbn(phone, isbn);
        if (book == null){
            return false;
        }else {
            return true;
        }

    }

    @Override
    public boolean insertCollectByPhoneAndIsbn(String phone, String isbn) {
        return bookMapper.insertCollectByPhoneAndIsbn(phone,isbn);
    }

    @Override
    public boolean delCollectByPhoneAndIsbn(String phone, String isbn) {
        return bookMapper.delCollectByPhoneAndIsbn(phone,isbn);
    }
}
